<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Image Upload Example</title>
</head>

<body>
    <input type="file" id="imageInput" />
    <button onclick="sendRequest()">发送包含图片数据的请求</button>
    <div id="loading" style="display:none;">正在加载，请稍候...</div> <!-- 添加加载提示元素 -->
    <script>
        function readFileAsBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onloadend = () => {
                    resolve(reader.result);
                };
                reader.onerror = reject;
                reader.readAsDataURL(file);
            });
        }

        async function sendRequest() {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://127.0.0.1:5000/predict', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            const fileInput = document.getElementById('imageInput');
            const file = fileInput.files[0];
            if (file) {
                document.getElementById('loading').style.display = 'block'; // 显示加载提示
                const base64Image = await readFileAsBase64(file);
                const data = {
                    "image": base64Image,
                    "image_name": file.name
                };
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        document.getElementById('loading').style.display = 'none'; // 隐藏加载提示
                        if (xhr.status === 200) {
                            const response = JSON.parse(xhr.responseText);
                            console.log(response);
                            // 后续页面更新操作
                        } else {
                            console.error(`请求失败，状态码: ${xhr.status}`);
                            // 错误提示细化等逻辑
                        }
                    }
                };
                xhr.send(JSON.stringify(data));
            } else {
                console.error("请选择一张图片");
            }
        }
    </script>
</body>

</html>